<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 关注
 *
 */
class Attentions extends CI_Controller {
	private $uid;
	function __construct()
	{
		parent::__construct();
		$this->load->model('usermodel');
		$this->uid = $this->usermodel->get_id_by_token($this->input->post('token'));
		//加载model
		$this->load->model('attentionsmodel');
	}
	public function index()
	{
		//默认是我关注的人
		$this->myattentions();
	}
	
	/**
	 * 推荐关注
	 *
	 */
	public function recommendation()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$this->dblib->set_query_limit();
		$this->db->select('u1.id, u1.name, u1.photo, u1.reg_type, count(app1.name) as samesofts')
				->from('user as u1')
				->join('app as app1', 'app1.uid=u1.id')
				->where('u1.id <>', $this->uid)
				->where("app1.name in (SELECT app2.name FROM app AS app2 JOIN user AS u2 ON u2.id=app2.uid WHERE u2.id='$this->uid')")
				->group_by('u1.id')
				->order_by('samesofts', 'desc')
				->limit(20);
		$query = $this->db->get();

		if($query->num_rows() > 0){
			$this->load->library('uploadimglib');
			$result = $query->result_array();
			//设置photo路径
			foreach ($result as $k=>$v){
				$result[$k]['photo'] = $this->uploadimglib->re_image_path($v['photo'], $v['reg_type']);
				unset($result[$k]['reg_type']);//不需要此字段
			}
			//输出最终的xml
			echo $this->xmllib->get_xml($result, array('recommendation'), 'recommendations');
			exit;
		}else{
			//没有推荐关注
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 我关注的人
	 *
	 */
	public function myattentions()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		//加载dblib
		//$this->load->library('dblib');
		/*$this->dblib->set_query_limit();
		$this->db->select('u1.id, u1.name, u1.photo, count(app1.name) as samesofts')
				->from('user as u1')
				->join('attentions as a', 'u1.id=a.attentionid')
				->join('app as app1', 'app1.uid=a.attentionid')
				->where('a.uid', $this->uid)
				->where("app1.name in (SELECT app2.name FROM app AS app2 JOIN user AS u2 ON u2.id=app2.uid WHERE u2.id='$this->uid')")
				->group_by('u1.id')
				->order_by('samesofts', 'desc');*/
		
		$attentions = $this->attentionsmodel->get_attentions($this->uid);
		
		if(count($attentions) > 0){
			foreach ($attentions as $k=>$attention) {

				//查找相同应用数目
				$this->db->select('count(app1.name) as samesofts')
						 ->from('app as app1')
						 ->where('app1.uid', $attention['uid'])
						 ->where("app1.name in (SELECT app2.name FROM app AS app2 JOIN user AS u2 ON u2.id=app2.uid WHERE u2.id='$this->uid')")
						 ->group_by('app1.uid');
				$query = $this->db->get();
				$samesofts = $query->row_array();
				$samesofts = count($samesofts) > 0 ? $samesofts['samesofts'] : 0;
				$attentions[$k]['samesofts'] = $samesofts;
			}
			
			//查询关注了多少人
			$this->db->select('count(*) as count')
						->from('attentions')
						->where('uid', $this->uid);
			$query = $this->db->get();
			$row = $query->row_array();
			$attentions_count = $row['count'];//关注人数
			
			$this->xmllib->append_xml('attentions_count', $attentions_count);

			//输出最终的xml
			echo $this->xmllib->get_xml($attentions, array('attention'), 'myattentions');
			exit;
		}else{
			//没有关注的人
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 我关注的人的动态
	 *
	 */
	function myattentionuser_actives()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		//获取我关注的人uid
		//加载attentionsmodel
		$this->load->model('attentionsmodel');
		//返回 userids
		$attentionuserids = $this->attentionsmodel->get_myattentions_user_id($this->uid);
		if($attentionuserids){
			//处理数组
			$ids = array();
			foreach ($attentionuserids as $attentionsuser){
				$ids[] = $attentionsuser['attentionid'];
			}
			unset($attentionuserids);//释放

			$actives = $this->_get_attentionsuser_actives($ids);
			
			//输出最终的xml
			echo $this->xmllib->get_xml($actives, array('active'), 'actives');
			exit;
		}else{
			//为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 查看别人关注的人
	 *
	 */
	function other_myattentions()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$uid = $this->input->post('uid');
		$attentions = $this->attentionsmodel->get_attentions($uid);
		if(count($attentions) > 0){
			foreach ($attentions as $k=>$v){
				if($this->attentionsmodel->check_attention($this->uid, $v['uid'])){
					//当前用户关注过此用户
					$attentions[$k]['have_attention'] = 1;
				}else{
					$attentions[$k]['have_attention'] = 0;
				}
			}
			//查询关注了多少人
			$this->db->select('count(*) as count')
						->from('attentions')
						->where('uid', $uid);
			$query = $this->db->get();
			$row = $query->row_array();
			$attentions_count = $row['count'];//关注人数
			$this->xmllib->append_xml('attentions_count', $attentions_count);
			//输出最终的xml
			echo $this->xmllib->get_xml($attentions, array('attention'), 'myattentions');
			exit;
		}else{
			//没有关注
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 添加关注
	 *
	 */
	function addattention()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$attentionid = $this->input->post('attentionid');
		if (empty($attentionid)) {
			//非法操作
			echo $this->xmllib->error_xml('关注的用户无效');
			exit;
		}
		
		if($attentionid == $this->uid){
			//非法操作
			echo $this->xmllib->error_xml('不能关注自己哦');
			exit;
		}
		//查询要关注的用户是否存在
		$this->load->model('usermodel');
		if(!$this->usermodel->check_user_by_id($attentionid)){
			//关注的人不存在
			echo $this->xmllib->error_xml('关注的用户不存在');
			exit;
		}
		
		//检测关注的此用户之前有没有已经关注过了
		if($this->attentionsmodel->check_attention($this->uid, $attentionid)){
			//已经关注过
			echo $this->xmllib->error_xml('您已经关注过此用户，请不要重复关注');
			exit;
		}
		
		//添加关注
		if($this->attentionsmodel->insert_attention($this->uid, $attentionid)){
			//添加关注成功
			//添加动态
			$this->load->model('activemodel');
			$this->activemodel->insert_active(array('uid' 			=> $this->uid,
													'active_id'		=> $attentionid,
													'active_type'	=> ATTENTION_ACTIVE,
													'memo'			=> '关注了'));
			
			echo $this->xmllib->success_xml('添加关注成功');
			exit;
		}else{
			//添加关注失败
			echo $this->xmllib->error_xml('添加关注失败，请稍后再试');
			exit;
		}
	}
	
	/**
	 * 批量关注
	 *
	 */
	function addattentions()
	{
		//加载表单验证类库
  		$this->load->library('form_validation');
  		
		header('Content-type:text/xml');// 向浏览器输出 xml
		$_POST['attentionid_list'] = isset($_POST['attentionid_list']) ? $_POST['attentionid_list'] : '';//此处设置时为了防止生成xml报错
		
		$this->form_validation->set_rules('attentionid_list', '', 'trim|required');
		$this->form_validation->set_message('required', '没有选择要关注的人');
		
		$this->form_validation->set_error_delimiters('', '');
		if ($this->form_validation->run() == FALSE){
			$attentionid_list_error = form_error('attentionid_list');
			echo $this->xmllib->error_xml($attentionid_list_error);
			exit;
		}
		
		$attentionid_list = $this->input->post('attentionid_list');
		$attentionid_arr = explode(',', trim($attentionid_list, ','));
		if(count($attentionid_arr) >0 ){
			//加载user model
			$this->load->model('usermodel');
			//加载active model
			$this->load->model('activemodel');
		
			foreach ($attentionid_arr as $attentionid){
				if(empty($attentionid)) continue;
				//不能关注自己
				if($attentionid == $this->uid) continue;
				//查询要关注的用户是否存在
				if(!$this->usermodel->check_user_by_id($attentionid)) continue;
				//检测是否之前已经关注过
				if($this->attentionsmodel->check_attention($this->uid, $attentionid)) continue;
				//添加关注
				$this->attentionsmodel->insert_attention($this->uid, $attentionid);
				
				//添加动态
				$this->activemodel->insert_active(array('uid' 			=> $this->uid,
														'active_id'		=> $attentionid,
														'active_type'	=> ATTENTION_ACTIVE,
														'memo'			=> '关注了'));
			}
			//成功提示
			echo $this->xmllib->success_xml('添加关注成功');
			exit;
		}else{
			//添加失败
			echo $this->xmllib->error_xml('添加关注失败，请稍后再试');
			exit;
		}
	}
	
	/**
	 * 取消关注
	 *
	 * @param unknown_type $attentionid
	 */
	function delattention()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$attentionid = $this->input->post('attentionid');
		if (empty($attentionid)) {
			//非法操作
			echo $this->xmllib->error_xml('关注的用户无效');
			exit;
		}
		//检测要取消关注的用户当前用户是不是关注了
		if(!$this->attentionsmodel->check_attention($this->uid, $attentionid)){
			//当前用户并没有关注要取消关注的用户，是个非法操作哦
			echo $this->xmllib->error_xml('您没有关注此用户，故不能执行取消关注操作');
			exit;
		}
		
		//执行取消关注
		if($this->attentionsmodel->delete_attention($this->uid, $attentionid))
		{
			//执行成功
			//加载active model
			$this->load->model('activemodel');
			//添加动态
			$this->activemodel->insert_active(array('uid' 			=> $this->uid,
													'active_id'		=> $attentionid,
													'active_type'	=> ATTENTION_ACTIVE,
													'memo'			=> '取消关注'));
														
			echo $this->xmllib->success_xml('取消关注成功');
			exit;
		}else{
			//执行失败
			echo $this->xmllib->error_xml('取消关注失败，请稍候再试');
			exit;
		}
	}
	
	//获取个人动态
	function _get_attentionsuser_actives($uid=array())
	{
		//获取动态信息
		$this->dblib->set_query_limit();
		$this->db->select('u.name as user_name, u.id as user_id, u.photo as user_photo, u.reg_type, a.createtime as active_createtime, (UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(a.createtime)) as diff_time, a.active_id, a.active_type, a.memo as active_memo')
				 ->from('active as a')
				 ->join('user as u', 'u.id=a.uid')
				 ->where_in('u.id', $uid)
				 ->order_by('active_createtime', 'desc');
		$query = $this->db->get();
		$actives = $query->result_array();
		//加载timelib库，处理时间格式
		$this->load->library('timelib');
		foreach ($actives as $k=>&$active){
			//设置图片路径
			$this->load->library('uploadimglib');
			$actives[$k]['user_photo'] = $this->uploadimglib->re_user_photo($active['user_photo'], $active['reg_type']);
			unset($actives[$k]['reg_type']);//不需要此字段
			$actives[$k]['diff_time'] = $this->timelib->diff_time($active['diff_time']);
			switch ($active['active_type']){
				case APP_ACTIVE:
					//应用
					$this->db->select('a.id, a.name, a.photo, c.share_or_comment, c.content')
							 ->from('app as a')
							 ->join('comments as c', "a.id=c.comment_id AND c.uid='$active[user_id]' AND c.comment_type=" . APP_COMMENT, 'left')
							 ->where('a.id', $active['active_id']);
					$query = $this->db->get();
					$row = $query->row_array();
					$actives[$k] = array_merge($active, $row);
					$row['photo'] && $actives[$k]['photo'] = $this->uploadimglib->re_image_path($row['photo']);
					break;
				case ALBUM_ACTIVE:
					//专辑
					$this->db->select('a.id, a.name, c.share_or_comment, c.content')
							 ->from('album as a')
							 ->join('comments as c', "a.id=c.comment_id AND c.uid='$active[user_id]' AND c.comment_type=" . ALBUM_COMMENT, 'left')
							 ->where('a.id', $active['active_id']);
					$query = $this->db->get();
					$row = $query->row_array();
					$actives[$k] = array_merge($active, $row);
					break;
				case ATTENTION_ACTIVE:
					//关注
					$this->db->select('id, name, photo, reg_type')
							 ->from('user')
							 ->where('id', $active['active_id']);
					$query = $this->db->get();
					$row = $query->row_array();
					$row['photo'] = $this->uploadimglib->re_user_photo($row['photo'], $row['reg_type']);
					unset($row['reg_type']);//不需要
					$actives[$k] = array_merge($active, $row);
					break;
			}
		}
		
		return $actives;
	}
}

/* End of file attentions.php */
/* Location: ./application/controllers/attentions.php */